<template>
  <div class="drawer">
    <el-descriptions title="唯一标识：">
      <el-descriptions-item label="创建人：">{{detailInfo?.cme_create_by|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="创建日期：">{{detailInfo?.cme_create_date|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型名称：">{{detailInfo?.cme_name|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型图标：">
        <div style="display: inline-block;">
          <img :src="'./cmdb/'+detailInfo.cme_icon+'.svg'" alt="" style="width: 40px;height: 40px;" />
        </div>
      </el-descriptions-item>

      <el-descriptions-item label="所属分组：">{{detailInfo?.cmc_name|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型类型：">{{detailInfo?.cme_type==1?'软件类型':detailInfo?.cme_type==2?'硬件类型' :'' || '-'}}</el-descriptions-item>
    </el-descriptions>

    <el-card style="max-width: 100%">
      <template #header>
        <div class="card-header">
          <el-button type="primary" plain @click="addGroup" v-has-permi="['cmdb:modelGroup:add']">添加分组</el-button>
        </div>
      </template>
      <el-collapse v-model="collapseFlag" v-if="detailInfo.groups">
        <el-collapse-item :title="groups.cmeg_name" :name="groups.cmeg_key" v-for="(groups, index) in detailInfo?.groups" :key="index">
          <template #title>
            <div>
              <span style="font-weight: 600;">{{groups.cmeg_name}}</span>
              <el-icon v-has-permi="['cmdb:modelGroup:edit']" style="margin-left: 10px;cursor: pointer;" @click.stop="groupsEdit(groups)">
                <Edit />
              </el-icon>
              <el-icon v-has-permi="['cmdb:modelGroup:delete']" style="margin-left: 10px;cursor: pointer;" @click.stop="groupsDel(groups)">
                <Delete />
              </el-icon>
            </div> 
          </template>
          <div class="df card-item fw-w">
            <el-card v-for="(columns, columnsIndex) in groups.columns" :key="columnsIndex" style="margin-bottom:15px;">
              <div class="df ai-c">
                <div class="key-name"  ><span>{{columns.cmc_k_name}}</span>  </div>
                <div>
                  <svg-icon v-has-permi="['cmdb:modelKey:edit']" style="margin-left: 12px;" icon-class="edit" @click="keyEdit(columns)" />
                  <svg-icon v-has-permi="['cmdb:modelKey:delete']" style="margin-left: 12px;" icon-class="delete" @click="keyDel(columns)" />
                </div>
              </div>
            </el-card>
            <el-card class="add-card" v-has-permi="['cmdb:modelKey:add']" @click="addGroupKey(groups)" style="margin-bottom:15px;">
              <div class="df-c">  
                <el-icon>
                  <Plus />
                </el-icon>
                <span class="add-name">添加</span>
              </div>
            </el-card>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <!-- 添加分组弹框 -->
    <el-dialog v-model="addGroupVisible" :title="groupTitle" width="800" :close-on-click-modal="false">
      <el-form ref="GroupFormRef" style="max-width: 800px" :model="GroupForm" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item label="唯一标识:" prop="cmeg_key" :rules="[{required: true, validator: keyRules, trigger: 'blur' }]">
          <el-input v-model="GroupForm.cmeg_key" :disabled=" groupTitle == '编辑分组'" />
        </el-form-item>
        <el-form-item label="分组名称:" prop="cmeg_name" :rules="[{ required: true, message: '请输入分组名称' }]">
          <el-input v-model="GroupForm.cmeg_name" />
        </el-form-item>
        <el-form-item label="排序:" prop="cmeg_sort">
          <el-input type="number" v-model="GroupForm.cmeg_sort" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addGroupVisible = false">关闭</el-button>
          <el-button type="primary" @click="addGroupEnter"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加分组字段弹框 -->
    <el-dialog v-model="addGroupKeyVisible" :title="keyTitle" width="800" :close-on-click-modal="false">
      <el-form ref="GroupKeyFormRef" style="max-width: 800px" :model="GroupKeyForm" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item label="唯一标识:" prop="cmc_k_key" :rules="[{required: true, validator: keyRules, trigger: 'blur' }]">
          <el-input v-model="GroupKeyForm.cmc_k_key" :disabled="keyTitle == '修改字段'" />
        </el-form-item>
        <el-form-item label="字段名称:" prop="cmc_k_name" :rules="[{ required: true, message: '请输入字段名称' }]">
          <el-input v-model="GroupKeyForm.cmc_k_name" />
        </el-form-item>
        <el-form-item label="字段排序:" prop="cmc_k_sort">
          <el-input type="number" v-model="GroupKeyForm.cmc_k_sort" />
        </el-form-item>
        <el-form-item label="字段类型:" prop="cmc_k_type" :rules="[{ required: true, message: '请选择字段类型' }]">
          <el-select placeholder="请选择" v-model="GroupKeyForm.cmc_k_type">
            <el-option label="短字符" value="0" />
            <el-option label="长字符" value="1" />
            <el-option label="日期" value="2" />
            <el-option label="下拉框" value="3" />
            <el-option label="开关" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="下拉框列表" prop="" v-if="GroupKeyForm.cmc_k_type==3">
          <el-table :data="selectTableData" style="width: 100%" border>
            <el-table-column prop="key" label="label">
              <template #default="scope">
                <el-input type="text" placeholder="请输入" v-model="scope.row.key"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="value">
              <template #default="scope">
                <el-input type="text" placeholder="请输入" v-model="scope.row.value"></el-input>
              </template>
            </el-table-column>

            <el-table-column prop="" label="操作">
              <template #default="scope">
                <el-button @click="delSelect(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="partsAddTable"><el-button @click="addSelectList">添加列表</el-button></div>
        </el-form-item>

        <el-form-item label="字段设置:" prop="cmc_k_setting">
          <el-switch v-model="GroupKeyForm.cmc_k_setting" class="ml-2" width="60" inline-prompt active-text="非空" inactive-text="可为空" />
        </el-form-item>
        <el-form-item label="校验类型:" prop="cmc_k_ruleType" :rules="[{ required: true, message: '请选择校验类型' }]">
          <el-select placeholder="请选择" v-model="GroupKeyForm.cmc_k_ruleType">
            <el-option label="不校验" value="0" />
            <el-option label="正则" value="1" />
            <el-option label="系统参数" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="校验:" prop="cmc_k_rule">
          <el-input v-model="GroupKeyForm.cmc_k_rule" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="字段说明:" prop="cmc_k_remoke">
          <el-input v-model="GroupKeyForm.cmc_k_remoke" :rows="2" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addGroupKeyVisible = false">关闭</el-button>
          <el-button type="primary" @click="addGroupKeyEnter"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import {keyRules} from '../config'
import {modelDetailGroupAdd ,modelDetailGroupEdit ,modelDetailGroupDel ,modelDetailKeyAdd ,modelDetailKeyEdit,modelDetailKeyDel ,modelDetailList ,} from '@/api/cmdb/model'
const props = defineProps(['model_id'])
const collapseFlag = ref([]);

const data = reactive({
  addGroupVisible: false,
  GroupForm: { cmeg_key: "", cmeg_name: "", cmeg_sort: "" },
  addGroupKeyVisible:false,

  thisGroup:[],
  groupTitle:"",
  keyTitle:"",
  selectTableData:[{key:'',value:"" ,id:String(new Date().getTime())}]
})
const   GroupKeyForm = ref<any>({ cmc_k_key: "", cmc_k_name: "", cmc_k_sort: "" ,cmc_k_type:"",cmc_k_setting:false,cmc_k_ruleType:"",cmc_k_rule:"",cmc_k_remoke:""})
const { addGroupVisible, GroupForm ,addGroupKeyVisible ,thisGroup ,groupTitle,keyTitle,selectTableData} = toRefs(data)

const detailInfo = ref<any>([])
const GroupFormRef = ref()
/* 添加分组 */
const addGroup = async () => {
  groupTitle.value = '新建分组'
  addGroupVisible.value = true
  GroupForm.value = { cmeg_key: "", cmeg_name: "", cmeg_sort: "" }
  // const res = await
}
/* 编辑分组 */
const groupsEdit = async(row)=>{
  groupTitle.value = '编辑分组'
  console.log(row);
  addGroupVisible.value = true
  GroupForm.value =  { cmeg_key: row.cmeg_key, cmeg_name: row.cmeg_name, cmeg_sort: row.cmeg_sort ,_id:row._id }
}
/* 删除分组 */
const groupsDel  = (row)=>{
  ElMessageBox.confirm(
    `确认要删除"${row.cmeg_name}"分组吗`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res=  await modelDetailGroupDel(`${row.cme_key}/${row._id}/${row.cmeg_key}`)
      console.log(res);
      if(res.code==200){
        ElMessage.success('删除成功')
        await getModelDetail()
      }


    })
    .catch(() => {
    })
}
/* 添加分组确认 */
const addGroupEnter = async()=>{
  GroupFormRef.value?.validate(async (valid: boolean) => {
    if(valid){
      console.log(GroupForm.value);
      const res = groupTitle.value == '新建分组'? await modelDetailGroupAdd({...GroupForm.value,cme_key:detailInfo.value.cme_key,cme_id:detailInfo.value._id}) :await modelDetailGroupEdit({...GroupForm.value,cme_key:detailInfo.value.cme_key,cme_id:detailInfo.value._id})
        console.log(res);
        if(res.data){
          ElMessage.success(groupTitle.value+'成功')
          addGroupVisible.value = false
          await getModelDetail()
        }
    }
  })
}

const GroupKeyFormRef = ref()
/* 添加分组字段 */
const addGroupKey = async(row)=>{
  console.log(row);
  keyTitle.value = '新建字段'
  thisGroup.value = row
  addGroupKeyVisible.value = true
  GroupKeyForm.value ={}
}
/* 字段修改 */
const keyEdit = (row)=>{
  console.log(row);
  if(row.cmc_k_type==3){  selectTableData.value = row.cmc_k_select_list}



  keyTitle.value = '修改字段'
  addGroupKeyVisible.value = true
  GroupKeyForm.value = row
}
/* 字段删除 */
const keyDel = (row)=>{
  console.log(row);

  ElMessageBox.confirm(
    `确认要删除"${row.cmc_k_name}"字段吗`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res=  await modelDetailKeyDel(`${row._id}`)
      console.log(res);
      if(res.code==200){
        ElMessage.success('删除成功')
        await getModelDetail()
      }


    })
    .catch(() => {
    })
}

/* t添加分组字段提交 */
const addGroupKeyEnter = ()=>{
  console.log(thisGroup.value);
  console.log(GroupKeyForm.value);

  console.log(selectTableData.value);


  let isTableFlag  = true
  selectTableData.value.forEach(item=>{
    if(!item.key || !item.value){
      isTableFlag = false
    }
  })
  if(!isTableFlag && GroupKeyForm.value.cmc_k_type==3 ){
    ElMessage.warning('请查看下拉表格是否填写完整')
    return false
  }



   if(GroupKeyForm.value.cmc_k_type ==3 ){
    GroupKeyForm.value['cmc_k_select_list'] = selectTableData.value
   }else {

    GroupKeyForm.value['cmc_k_select_list'] = undefined

   }





  GroupKeyFormRef.value?.validate(async (valid: boolean) => {
    if(valid){
      console.log(GroupKeyForm.value);
      if(valid){
        // cmeg_key:'详情分组中的唯一标识'
        const res =  keyTitle.value == '新建字段'? await modelDetailKeyAdd({...GroupKeyForm.value,cme_key:thisGroup.value.cme_key,cmeg_key:thisGroup.value.cmeg_key}) :  await modelDetailKeyEdit({...GroupKeyForm.value})
        console.log(res);
          if(res.data){
            ElMessage.success( keyTitle.value+'成功')
            addGroupKeyVisible.value = false
            await getModelDetail()
          }
      }

    }
  })

}
/* 添加下拉框列表 */
const addSelectList = async()=>{
  selectTableData.value.push({key:'',value:"" ,id:String(new Date().getTime())})
}

/* 删除备件列表 */
const delSelect = (row)=>{
  if(selectTableData.value&& selectTableData.value.length==1){
    ElMessage.error('下拉框类型至少有一条数据');

    return false
  }
  selectTableData.value = selectTableData.value.filter(item=>item.id!=row.id)
}

/* 获取模型的详情 */
const getModelDetail = async()=>{
  const res = await modelDetailList(props.model_id)
  console.log(res);
  detailInfo.value = res.data
  detailInfo.value?.groups&& detailInfo.value.groups.forEach(element => { //默认展开
    collapseFlag.value.push(element.cmeg_key)
  });
}

defineExpose({
  getModelDetail
})
</script>

<style scoped lang="scss">
.drawer {
  .card-item {
    .el-card {
      margin-left: 15px;

    }

    .add-card {
      cursor: pointer;

      .add-name {
        padding-left: 6px;
      }
    }
    .key-name{
      >span{
  
      }
    }
  }
}

:deep(.el-card__body) {
  padding: 15px !important;
}
</style>
